#!/bin/bash
# usage: <command> <file> <colNum>
if [ $# -eq 2 ]; then
    input=$1
    colNum=$2
else
    input=-
    colNum=$1
fi

if [ "$2" == "-s" ]; then
    awk -v colNum=$colNum '
        BEGIN{OFS="\t"; total=0;}
        { total += 1; x=$colNum; if (! a[x]) a[x] = 0;a[x] += 1;}
        END{for (x in a){printf "%s\t%d\t%.2f%%\n", x, a[x], a[x]/total * 100}; print "total", total, "100.00%"}
    ' $input
else
    awk -v colNum=$colNum '
        BEGIN{FS="\t"; OFS="\t"; total=0;}
        { total += 1; x=$colNum; if (! a[x]) a[x] = 0;a[x] += 1;}
        END{for (x in a){printf "%s\t%d\t%.2f%%\n", x, a[x], a[x]/total * 100}; print "total", total, "100.00%"}
    ' $input
fi
